package com.boruan.shengtangfeng.admin.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.boruan.shengtangfeng.admin.jwt.UserSubject;
import com.boruan.shengtangfeng.admin.jwt.util.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.SQLReady;
import org.beetl.sql.core.db.KeyHolder;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.boruan.shengtangfeng.core.dao.ISystemUserDao;
import com.boruan.shengtangfeng.core.dao.ISystemUserRoleDao;
import com.boruan.shengtangfeng.core.dto.SystemUserDto;
import com.boruan.shengtangfeng.core.dto.mapper.SystemUserDtoMapper;
import com.boruan.shengtangfeng.core.entity.Log;
import com.boruan.shengtangfeng.core.entity.Log.LogType;
import com.boruan.shengtangfeng.core.entity.Log.OperateType;
import com.boruan.shengtangfeng.core.entity.Role;
import com.boruan.shengtangfeng.core.entity.SystemUser;
import com.boruan.shengtangfeng.core.entity.SystemUserRole;
import com.boruan.shengtangfeng.core.service.ILogService;
import com.boruan.shengtangfeng.core.service.IRoleService;
import com.boruan.shengtangfeng.core.service.ISystemUserService;
import com.boruan.shengtangfeng.core.service.IUploadFileService;
import com.boruan.shengtangfeng.core.utils.GlobalReponse;
import com.boruan.shengtangfeng.core.utils.UserUtil;
import com.boruan.shengtangfeng.core.vo.SystemUserVo;
import com.boruan.shengtangfeng.core.vo.mapper.SystemUserVoMapper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @author: lihaicheng
 * @Description: 系统人员管理
 * @date:2020年3月10日 上午11:14:10
 */
@Slf4j
@RestController
@RequestMapping("/admin/systemUser")
@SuppressWarnings("all")
@Api(value = "", tags = { "NO:6 系统用户相关接口" })
public class SystemUserApi {
	@Autowired
	private ISystemUserService systemUserService;
	@Autowired
	private ILogService sysLogService;
	@Autowired
	private IRoleService roleService;
	@Autowired
	private IUploadFileService uploadFileService;
	@Autowired
	private ISystemUserDao systemUserDao;
    @Autowired
	private ISystemUserRoleDao systemUserRoleDao;
	/**
	 * @author: Jessica
	 * @Description: 分页获取
	 * @date:2020年3月10日 上午11:14:10
	 **/
	@PostMapping(value = "/page")
	@ApiOperation(value = "NO:6-1 分页获取系统用户", notes = "")
	public GlobalReponse<PageQuery<SystemUser>> page(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
			SystemUser systemUser, Model model) {
		PageQuery<SystemUser> query = new PageQuery<SystemUser>();
		query.setPageNumber(pageNo);
		systemUserService.pageQuery(query, systemUser);
		model.addAttribute("page", query);
		return GlobalReponse.success(query);
	}

	@CrossOrigin
	@GetMapping(value = "/pageSystemUser")
	@ApiOperation(value = "NO:13-3 查看课程列表", notes = "")
	public GlobalReponse<SystemUserVo> pageSystemUser(SystemUserDto systemUserDto, @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
											 @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
		PageQuery<SystemUser> pageData = new PageQuery<SystemUser>();
		pageData.setPageNumber(pageIndex);
		pageData.setPageSize(pageSize);
		SystemUser systemUser = SystemUserDtoMapper.MAPPER.toEntity(systemUserDto);
		systemUserService.pageSystemUser(pageData, systemUser);
		return GlobalReponse.success().setData(pageData);
	}
	/**
	 * @author: lihaicheng
	 * @Description: 详情
	 * 
	 * @date:2020年3月10日 上午11:14:10
	 **/
	@GetMapping(value = "/get")
	@ApiOperation(value = "NO:6-2 获取系统用户详情", notes = "")
	public GlobalReponse<SystemUser> get(Long id, Model model) {
		SystemUser systemUser = systemUserService.findById(id);
		List<Role> roles = roleService.findSysRole();
		GlobalReponse reponse = GlobalReponse.success(systemUser);
		reponse.setData1(roles);
		return reponse;
	}
	/**
	 * @author: lihaicheng
	 * @Description: 详情
	 * 
	 * @date:2020年3月10日 上午11:14:10
	 **/
	@GetMapping(value = "/getCurrent")
	@ApiOperation(value = "NO:6-2 获取系统用户详情", notes = "")
	public GlobalReponse<SystemUserVo> getCurrent(Model model) {
	    UserSubject userSubject = JwtUtil.getCurrentJwtUser();
	    SystemUser systemUser = systemUserService.findById(userSubject.getId());
	    GlobalReponse reponse = GlobalReponse.success(SystemUserVoMapper.MAPPER.toVo(systemUser));
	    return reponse;
	}

	/**
	 * @author: lihaicheng
	 * @Description: 详情
	 * @date:2020年3月10日 上午11:14:10
	 **/
	@PostMapping(value = "/doUpdateMyPassword")
	@ApiOperation(value = "NO:6-3 更新当前登录系统用户的密码", notes = "")
	public GlobalReponse doUpdateMyPassword(Model model, String password, String oldPassword) {
		UserSubject userSubject = JwtUtil.getCurrentJwtUser();
		SystemUser systemUser = systemUserService.findById(userSubject.getId());
		if (UserUtil.match(oldPassword, systemUser.getPassword(), systemUser.getSalt())) {
			systemUser.setPassword(password);
			systemUserService.saveWithPassword(systemUser);
			return GlobalReponse.success();
		} else {
			return GlobalReponse.fail("旧密码错误");
		}
	}
	@PostMapping(value = "/saveSystemUser")
	@ApiOperation(value = "NO:6-4 添加系统用户", notes = "")
	public GlobalReponse add(@RequestBody SystemUserDto systemUserDto) {
		try{
			UserSubject userSubject = JwtUtil.getCurrentJwtUser();
			Log sysLog = new Log();
			SystemUser systemUser=SystemUserDtoMapper.MAPPER.toEntity(systemUserDto);
			if (systemUser.getId() == null) {
				systemUser.setCreateBy(userSubject.getName());
				systemUser.setCreateTime(new Date());
				systemUser.setIsDeleted(false);
				systemUser.setSalt(UserUtil.getSalt());
				systemUser.setPassword(UserUtil.entryptPassword(systemUser.getPassword(), systemUser.getSalt()));
				KeyHolder kh = systemUserDao.insertReturnKey(systemUser);


				systemUser.setId(kh.getLong());
				SystemUserRole systemUserRole=new SystemUserRole();
				systemUserRole.setSystemUserId(systemUser.getId());
				systemUserRole.setRoleId(systemUserDto.getRoleId());
				systemUserRoleDao.insert(systemUserRole);
			} else {
				systemUser.setUpdateBy(userSubject.getName());
				systemUser.setUpdateTime(new Date());
				systemUser.setIsDeleted(false);
				systemUser.setSalt(UserUtil.getSalt());
				systemUser.setPassword(UserUtil.entryptPassword(systemUser.getPassword(), systemUser.getSalt()));
				systemUserDao.updateTemplateById(systemUser);

				systemUserRoleDao.getSQLManager().executeUpdate(new SQLReady("update system_user_role set role_id = ? where system_user_id = ?", systemUserDto.getRoleId(), systemUser.getId()));
			}
			return GlobalReponse.success();
		}catch (Exception e){
			log.error("管理员添加系统用户信息失败:{}", e);
			return GlobalReponse.fail();
		}
	}
	@PostMapping(value = "/add")
	@ApiOperation(value = "NO:6-4 添加系统用户", notes = "")
	public GlobalReponse add(SystemUser systemUser, @RequestParam(required = false) Long roleId) {
		try {
			UserSubject userSubject = JwtUtil.getCurrentJwtUser();
			Log sysLog = new Log();
			if (systemUser.getId() == null) {
				// 添加
				systemUser.setCreateBy(userSubject.getName());
				systemUser.setCreateTime(new Date());
				systemUser.setIsDeleted(false);
				boolean lean = systemUserService.save(systemUser, roleId);
				if (!lean) {
					return GlobalReponse.fail();
				}
				sysLog.setObjectId(systemUser.getId());
				sysLog.setContent("管理员添加系统用户信息");
				sysLog.setOperateType(OperateType.ADD);
			}
			sysLog.setCreateTime(new Date());
			sysLog.setOperater(userSubject.getId());
			sysLog.setLogType(LogType.ADMIN);
			sysLogService.save(sysLog);
			return GlobalReponse.success();
		} catch (Exception e) {
			log.error("管理员添加系统用户信息失败:{}", e);
			return GlobalReponse.fail();
		}
	}

	@PostMapping(value = "/updateUserRole")
	@ApiOperation(value = "NO:6-5 更新系统用户的角色", notes = "")
	public GlobalReponse updateUserRole(String check, Long userId) {
		SystemUser user = systemUserService.findById(userId);
		UserSubject userSubject = JwtUtil.getCurrentJwtUser();
		String[] checkList = check.split(",");
		List<Long> roleIds = new ArrayList<Long>();
		for (int i = 0; i < checkList.length; i++) {
			if (StringUtils.isNotBlank(checkList[i])) {
				roleIds.add(Long.valueOf(checkList[i].toString()));
			}
		}
		try {
			systemUserService.updateUserRole(user, roleIds);
			Log sysLog = new Log();
			sysLog.setContent("用户管理分配岗位");
			sysLog.setCreateTime(new Date());
			sysLog.setOperater(userSubject.getId());
			sysLog.setObjectId(userSubject.getId());
			sysLog.setLogType(LogType.ADMIN);
			sysLog.setOperateType(OperateType.UPDATE);
			sysLogService.save(sysLog);
			return GlobalReponse.success();
		} catch (Exception e) {
			log.error("用户管理分配岗位失败:{}", e.getMessage());
			return GlobalReponse.fail();
		}
	}

	/**
	 * @author: lihaicheng
	 * @Description: 删除
	 * @date:2020年3月10日 上午11:14:10
	 **/
	@GetMapping(value = "/delete")
	@ApiOperation(value = "NO:6-6 删除系统用户", notes = "")
	public GlobalReponse delete(Long id) {
		if (id == 1) {
			return GlobalReponse.fail("超级管理员是神圣不可侵犯的！");
		}
		UserSubject userSubject = JwtUtil.getCurrentJwtUser();
		Log sysLog = new Log();
		sysLog.setContent("删除系统用户");
		sysLog.setCreateTime(new Date());
		sysLog.setOperater(userSubject.getId());
		sysLog.setObjectId(userSubject.getId());
		sysLog.setLogType(LogType.ADMIN);
		sysLog.setOperateType(OperateType.DELETE);
		sysLogService.save(sysLog);
		return systemUserService.delete(id);
	}

	/**
	 * 获取一个用户的角色
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping(value = "/getRoles")
	@ApiOperation(value = "NO:6-7 获取一个系统用户的角色", notes = "")
	public GlobalReponse<SystemUser> getRoles(Long id, Model model) {
		SystemUser systemUser = systemUserService.findUserAndRole(id);
		List<Role> roles = roleService.findAll();
		GlobalReponse reponse = GlobalReponse.success(systemUser);
		reponse.setData1(roles);
		return reponse;
	}

	/**
	 * 
	 * @author:Jessica
	 * @Descrition:教师端更换头像
	 * @date:2020年3月10日 上午11:14:10
	 * @param id
	 * @return
	 */
	@PostMapping(value = "/updateHeadImage")
	@ApiOperation(value = "NO:6-8 教师端更换头像", notes = "")
	public GlobalReponse updateHeadImage(MultipartFile file) {
		UserSubject userSubject = JwtUtil.getCurrentJwtUser();
		SystemUser systemUser = systemUserService.findById(userSubject.getId());
		GlobalReponse imageFile = uploadFileService.uploadImageFile(file, userSubject.getId());
		Object data = imageFile.getData();
		if (data.toString() != null && data.toString() != "") {
			systemUser.setHeadImage(data.toString());
			systemUserService.save(systemUser, userSubject.getId());
			return GlobalReponse.success("更换头像成功");
		} else {
			return GlobalReponse.fail("更换头像失败");
		}

	}

}
